import React from 'react'
import './index.scss'
export default class Index extends React.Component {
  constructor() {
    super()
    this.state = {}
  }
  into(key) {
    let { target, box1, box2 } = this.refs
    if (key === 1) {
      box1.appendChild(target)
    } else {
      box2.appendChild(target)
    }
  } 
  dragStart(e) {
    e.preventDefault()
    e.stopPropagation()
    e.dataTransfer.setData('obj', e.target)
  }
  dragOver(e) {
    e.preventDefault()
    e.stopPropagation()
    console.log(e.dataTransfer.getData('obj'))
  }
  drop(e) {
    e.preventDefault()
    e.stopPropagation()
    let file = e.dataTransfer.files[0]
    if (file.name.indexOf('.txt') !== -1) {
      this.showTxtFile(file)
    } else {
      this.showImageFile(file)
    }
  }
  showTxtFile(file_blob) {
    let reader = new FileReader()
    reader.readAsBinaryString(file_blob)
    reader.onload = () => {
      this.refs.box3.innerHTML = "<div>" + reader.result +"</div>"
    }
  }
  showImageFile(file_blob) {
    let reader = new FileReader()
    reader.readAsDataURL(file_blob)
    reader.onload = () => {
      this.refs.box3.innerHTML = "<img src='" + reader.result +"'/>"
    }
  }
  render() {
    return (
      <div className="drag">
        <div ref="target" className="target" draggable="true" onDragStart={(e) => this.dragStart(e)}>被移动</div>
        <div ref="box1" draggable="true" onClick={() => this.into(1)} className="drag_container">1</div>
        <div ref="box2" draggable="true" onClick={() => this.into(2)} className="drag_container">2</div>
        <div ref="box3" draggable="true" onDragOver={(e) => this.dragOver(e)} onDrop={(e) => this.drop(e)} className="drag_container">3</div>
      </div>
    )
  }
}